<template>
  <div>
    <!-- :http-request-覆盖默认的上传行为，可以自定义上传的实现 -->
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="isShow" type="circle" :percentage="percentage" class="progress" />
    </el-upload>
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5')
// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKID2tTmpb5IFvJQGp77qJWOzLPCixvd4D5g',
  SecretKey: 'LPDl22mFRLyLQEl10i8IBn9D1YnkRs3x'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      percentage: 0,
      isShow: false
    }
  },
  methods: {
    // 上传图片的方法
    upload(files) {
      console.log(files)
      if (files.file) {
        this.isShow = true
        cos.putObject({
          Bucket: 'weiqing-1308159424', /* 必须 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: files.file.name, /* 必须 */
          StorageClass: 'STANDARD',
          Body: files.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percentage = parseInt(progressData.percent * 100)
            // console.log(JSON.stringify(progressData))
          }
        }, (err, data) => {
          if (err === null) {
            this.imageUrl = 'https://' + data.Location
            this.isShow = false
          }
        })
      }
    }

  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 160px;
    height: 160px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
